<template>
	<div class="goods-action">
		<van-goods-action>
		  <van-goods-action-icon 
				icon="bag" 
				text="购物车" 
				:badge="!bagCount ? '' : bagCount"
				:to="{name: 'Shopbag'}" />
		  <van-goods-action-icon 
				icon="like" 
				:text="isLike ? '已收藏' : '收藏'" 
				:color="isLike ? '#e74c3c' : '#323233'"
				@click="saveLike" />
		  <van-goods-action-button 
				type="warning" 
				text="加入购物车"
				@click="add" />
		  <van-goods-action-button 
				type="danger" 
				text="立即购买"
				@click="buy"/>
		</van-goods-action>
	</div>
</template>

<script>
	import {mapState} from 'vuex'
	import bus from '@/utils/eventBus.js'
	import { findLike, saveLike } from '@/api/detail.js'
	import { 
		getShopCartLength,
		addShopCart
	} from '@/api/order.js'
	export default {
		name: 'goods-action',
		data () {
			return {
				bagCount: 0, //购物车数量
				isLike: false, //是否以收藏
				pid: null
			}
		},
		created() {
			this.pid = this.$route.params.pid
			this._findLike()
			this._getShopCartLength()
		},
		// 路由缓存 执行
		activated() {
			if(!this.keepAlive) return
			this._findLike()
			this.pid = this.$route.params.pid
		},
		methods: {
			// 获取是否收藏
			_findLike() {
				const tokenString = window.sessionStorage.getItem('token')
				if(!tokenString) return
				findLike({
					pid: this.pid,
					tokenString
				})
				.then(({data: res}) => {
					console.log('是否收藏',res)
					if (res.code !== 1000 && !res.result ) return
					this.keepAlive = true
					if (res.result.length > 0) {
						this.isLike = true
					} else {
						this.isLike = false
					}
				})
				.catch(err => {
					this.$toast.fail('获取收藏失败,请重新尝试!')
				})
			},
			// 保存收藏状态
			saveLike () {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) return this.$toast('未登录')
				this.isLike = !this.isLike
				this.$toast.loading({
				  message: '加载中...',
				  forbidClick: true
				})
				saveLike(this.isLike, {
					pid: this.pid,
					tokenString
				})
				.then(({data: res}) => {
					console.log('点击收藏',res)
					this.$toast.success(res.msg)
					// 通知：我更新了收藏
					bus.$emit('update-like')
				})
				.catch(err => {
					this.isLike = !this.isLike
					this.$toast.fail('请求失败,请重新尝试!')
				})
			},
			// 获取购物车条数
			_getShopCartLength() {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) return this.$router.push({name: 'Login'})
				// 发起请求
				getShopCartLength({
					tokenString
				})
				.then(({data: res}) => {
					console.log('购物车条数', res)
					if (res.code !== 8000) return this.$toast.fail('请求异常,请重新尝试!')
					this.bagCount = res.result
				})
				.catch(err => {
					this.$toast.fail('请求失败,请重新尝试!')
				})
			},
			// 添加购物车请求（立即购买时需要先将商品加入购物车）
			_addShopbag (isBuy = false) {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) {
					this.$toast('未登录!')
					this.$router.push({name:'Login'})
					return 
				}
				// 参数
				let data = {
					tokenString,
					pid: this.pid,
					count: this.$store.state.selectCount,
					rule: ''
				}
				// 遍历获取 label 的 title
				let arr = []
				this.proDetailData.rules.forEach(item => {
					arr.push(item.rule[item.ruleIndex].title)
				})
				// 把title转化为字符串以/分割赋值给参数的rule
				data.rule = arr.join('/')
				// 加载中
				this.$toast.loading({
				  message: '加载中...',
				  forbidClick: true
				})
				// 发起请求
				addShopCart(data)
				.then(({data:res}) => {
					console.log('加入购物车',res)
					if (res.code !== 3000) return this.$route.push({ name: 'Login' })
					// 判断是购买还是加入购物车
					if (!isBuy) {
						if (res.status !== 1) return 
						this.$toast.success(res.msg)
						this.bagCount ++
					} else {
						this.$toast.clear()
						this.$router.push({ name: 'Pay', query: {sids: res.sid} })
					}
					// 发送通知：我添加了购物车
					bus.$emit('refresh-shop-cart')
				}).catch(err => {
					this.$toast.fail('请求失败,请重新尝试!')
				})
			},
			// 添加购物车
			add() {
				// 调用添加购物车请求
				this._addShopbag()
			},
			// 立即购买
			buy() {
				// 调用添加购物车请求
				this._addShopbag(true)
			}
		},
		computed: {
			...mapState(['selectCount','proDetailData'])
		}
	}
</script>

<style lang="scss" scoped>
	.goods-action{
		position: relative;
		z-index: 3;
		height: 50px;
		margin-top: 15px;
	}
</style>